package myapps.ttclient.activity;

import myapps.ttclient.GlobalVariables;
import myapps.ttclient.R;
import myapps.ttclient.app.TTClientApplication;
import myapps.ttclient.cryptography.ExponentialEncryptFunction;
import myapps.ttclient.protocol.message.AdminAuthentificationRequestMessage;
import myapps.ttclient.protocol.message.AdminAuthentificationResponseMessage;
import myapps.ttclient.protocol.message.KeyMemberAuthentificationRequestMessage;
import myapps.ttclient.protocol.message.KeyMemberAuthentificationResponseMessage;
import myapps.ttclient.protocol.message.NMSAuthentificationRequestMessage;
import myapps.ttclient.protocol.message.NMSAuthentificationResponseMessage;
import myapps.ttclient.protocol.message.NMSAuthenticationResetRequestMessage;
import myapps.ttclient.asymmetric_encryption.*;
import myapps.ttclient.baseclass_and_interface.TTClientMessage;
import myapps.ttclient.baseclass_and_interface.TTClientMessageReceiver;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.Toast;

public class AuthenticationSignInActivity extends Activity implements TTClientMessageReceiver {
	private static final int EMAIL_DIALOG = 0;

	private TTClientApplication application;

	private SharedPreferences preferences;

	private TabHost tabhost;

	private EditText etPassword;
	private Button btnSendAdminInfo;

	//private EditText etM;
	private EditText etI;
	private EditText etm;
	private EditText et_kExp;
	private EditText et_pExp;
	private EditText etEmailAddress;
	private EditText etEmailPassword;
//	private Button btnAutoFillEmail;
//	private Button btnManualFillEmail;
	private Button btnViewEmail;
	private Button btnSendToServer;
	private Button btnReset;
	
	private EditText etKMPassword;
	private Button btnSendKeyMemberInfo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		this.application = (TTClientApplication) this.getApplication();

		this.preferences = this.application.getPreferences();

		super.onCreate(savedInstanceState);

		////////////////////////////////////////////////////////////////////
		setContentView(R.layout.authentication_sign_in);

		tabhost = (TabHost) findViewById(R.id.tabhost);
		tabhost.setup();

		TabHost.TabSpec spec;

		spec = tabhost.newTabSpec("tab1");
		spec.setContent(R.id.tab1);
		spec.setIndicator("Admin", getResources().getDrawable(R.drawable.ic_tab_wifi));
		tabhost.addTab(spec);

		spec = tabhost.newTabSpec("tab2");
		spec.setContent(R.id.tab2);
		spec.setIndicator("NMS member", getResources().getDrawable(R.drawable.ic_tab_bluetooth));
		tabhost.addTab(spec);

		spec = tabhost.newTabSpec("tab3");
		spec.setContent(R.id.tab3);
		spec.setIndicator("Key member", getResources().getDrawable(R.drawable.ic_tab_bluetooth));
		tabhost.addTab(spec);
		
		tabhost.setCurrentTab(1);

		////////////////////////////////////////////////////////////////////////////////

		etPassword = (EditText) findViewById(R.id.etPassword);
		btnSendAdminInfo = (Button) findViewById(R.id.btnSendAdminInfo);
		btnSendAdminInfo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String password = etPassword.getText().toString();
				if(checkPasswordIsValid(password) == true) {
					try {
						byte[] encryptedPassword = RSA.rsaEncryptWithPublicKey(
								RSAKeyManager.getInstance().get_serverPublicKey(), 
								password.getBytes("UTF-16LE"));

						AuthenticationSignInActivity.this.application.sendMessage(
								new AdminAuthentificationRequestMessage(encryptedPassword));
					} catch(Exception ex) {
						AuthenticationSignInActivity.this.application.showToast("Must reconnect to server");

					}

					//AuthenticationActivity_SignIn.this.application.showToast("Sending admin info to server! Please wait...");
				} else {
					AuthenticationSignInActivity.this.application.showToast("Passwrod invalid");
				}
			}
		});

		//etM = (EditText) findViewById(R.id.et_M);
		etI = (EditText) findViewById(R.id.et_I);
		etm = (EditText) findViewById(R.id.et_m);
		et_kExp = (EditText) findViewById(R.id.et_kExp);
		et_pExp = (EditText) findViewById(R.id.et_pExp);

		btnSendToServer = (Button) findViewById(R.id.btnSendToServer);
		btnSendToServer.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					//String strM = etM.getText().toString();
					String strI = etI.getText().toString();
					String strm = etm.getText().toString();
					String strk = et_kExp.getText().toString();
					String strp = et_pExp.getText().toString();
					if (!isNumber(strI.toCharArray()) || !isNumber(strm.toCharArray())){
						AuthenticationSignInActivity.this.application.showToast("Incorrect input of (I, m). They must be a number");
						return;
					}

					//long M = Long.parseLong(strM);
					int mi = Integer.parseInt(strm);
					int I = Integer.parseInt(strI);
					int k = Integer.parseInt(strk);
					int p = Integer.parseInt(strp);

					//Send to server;
					//AuthenticationActivity_SignIn.this.application.showToast("Sending to server! Please wait...");
					//AuthenticationActivity_SignIn.this.application.showToast("Send");


					//Send request to connect to server
					
					//Encrypt I and mi by using k, p
					//........ do somethings 
					//////////////////////////////////
					int encoded_m = ExponentialEncryptFunction.ExponentalEncryt(mi, k, p);
					if (encoded_m == -1){
						String s = "Encode messages fail.\n" +
								   "m must be less than prime" +
								   "Try again before sending these!";
						Toast.makeText(AuthenticationSignInActivity.this, s, Toast.LENGTH_SHORT).show();
						return;
					}
					int encoded_I = ExponentialEncryptFunction.ExponentalEncryt(I, k, p);
					if (encoded_I == -1){
						String s = "Encode messages fail.\n" +
								   "I must be less than prime" +
								   "Try again before sending these!";
						Toast.makeText(AuthenticationSignInActivity.this, s, Toast.LENGTH_SHORT).show();
						return;
					}
					String value = "I = " + String.valueOf(encoded_I) + "\n" +
								   "m = " + String.valueOf(encoded_m);
					Toast.makeText(AuthenticationSignInActivity.this, value, Toast.LENGTH_LONG).show();
					try {
						AuthenticationSignInActivity.this.application.sendMessage(
								new NMSAuthentificationRequestMessage(encoded_m, encoded_I));

					} catch (Exception e) {
						e.printStackTrace();
					}

				} catch(Exception ex) {
					ex.printStackTrace();
				}
			}
		});

		btnViewEmail = (Button)findViewById(R.id.btnViewEmail);
		btnViewEmail.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent email = getPackageManager().getLaunchIntentForPackage("com.android.email");
				startActivity(email);
			}
		});
		
		etEmailAddress = (EditText)findViewById(R.id.etEmail_address);
		etEmailPassword = (EditText)findViewById(R.id.etEmail_password);
		
		
		btnReset = (Button) findViewById(R.id.btnReset);
		btnReset.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				on_btnReset_clicked();

			}
		});
		
		
		etKMPassword = (EditText) findViewById(R.id.etKMPassword);
		btnSendKeyMemberInfo = (Button) findViewById(R.id.btnSendKeyMemberInfo);
		btnSendKeyMemberInfo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String password = etKMPassword.getText().toString();
				if(checkPasswordIsValid(password) == true) {
					try {
						byte[] encryptedPassword = RSA.rsaEncryptWithPublicKey(
								RSAKeyManager.getInstance().get_serverPublicKey(), 
								password.getBytes("UTF-16LE"));

						AuthenticationSignInActivity.this.application.sendMessage(
								new KeyMemberAuthentificationRequestMessage(encryptedPassword));
					
					} catch(Exception ex) {
						AuthenticationSignInActivity.this.application.showToast("Must reconnect to server");

					}

					//AuthenticationActivity_SignIn.this.application.showToast("Sending admin info to server! Please wait...");
				} else {
					AuthenticationSignInActivity.this.application.showToast("Passwrod invalid");
				}
			}
		});

	}
	
	private void on_btnReset_clicked() {
		this.application.sendMessage(new NMSAuthenticationResetRequestMessage());
	}

	private boolean checkPasswordIsValid(String pw) {
		if(pw.length() >= 3) {
			return true;
		}
		return false;
	}

	private boolean isNumber(char[] s) {
		if (s.length == 0) {
			return false;
		}
		
		for (int i = 0; i < s.length; i++) {
			if (s[i] < '0' || s[i] > '9')
				return false;
		}
		
		return true;
	}

	@Override
	protected void onResume() {
		super.onResume();

		this.application.registerMessageReceiver(this);
	}

	@Override
	protected void onPause() {
		super.onPause();

		this.application.unregisterMessageReceiver(this);
	}

	@Override
	public void receiveMessage(TTClientMessage message) {

		if(message instanceof NMSAuthentificationResponseMessage) {
			NMSAuthentificationResponseMessage msg = (NMSAuthentificationResponseMessage) message;
			byte type = msg.type;
			String text = msg.text;

			if(type == NMSAuthentificationResponseMessage.TYPE_FAILED) {
				this.application.showToast(text);
			} else if(type == NMSAuthentificationResponseMessage.TYPE_NORMAL) {
				this.application.showToast(text);
			} else if(type == NMSAuthentificationResponseMessage.TYPE_SUCCESSFUL) {
				GlobalVariables.setCurrrentAuthority(GlobalVariables.AUTHORITY_MEMBER);
				this.application.showToast("Member");
				AuthenticationSignInActivity.this.finish();
			}
		} else if (message instanceof AdminAuthentificationResponseMessage) {
			AdminAuthentificationResponseMessage msg = (AdminAuthentificationResponseMessage) message;
			if(msg.authentificated) {
				try {
					GlobalVariables.setCurrrentAuthority(GlobalVariables.AUTHORITY_ADMIN);

					byte[] decryptedData = RSA.rsaDecryptWithPrivateKey(
							RSAKeyManager.getInstance().get_clientPrivateKey(), msg.encryptedTempKey);

					String tempKey = new String(decryptedData, "UTF-16LE");

					GlobalVariables.setTemporaryKey(tempKey);
					this.application.showToast("Administrator");

					AuthenticationSignInActivity.this.finish();
				} catch(Exception ex) {
					AuthenticationSignInActivity.this.application.showToast("Must reconnect to server");
				}
			} else {
				GlobalVariables.setCurrrentAuthority(GlobalVariables.AUTHORITY_GUEST);
				GlobalVariables.setTemporaryKey("");
				this.application.showToast("Authentication failed");
			}
		} else if (message instanceof KeyMemberAuthentificationResponseMessage) {
			KeyMemberAuthentificationResponseMessage msg = (KeyMemberAuthentificationResponseMessage) message;
			if(msg.authentificated == 1) {
				try {
					GlobalVariables.setCurrrentAuthority(GlobalVariables.AUTHORITY_KEY_MEMBER);

					byte[] decryptedData = RSA.rsaDecryptWithPrivateKey(
							RSAKeyManager.getInstance().get_clientPrivateKey(), msg.encryptedTempKey);

					String tempKey = new String(decryptedData, "UTF-16LE");

					GlobalVariables.setTemporaryKey(tempKey);
					this.application.showToast("Key Member");

					AuthenticationSignInActivity.this.finish();
				} catch(Exception ex) {
					AuthenticationSignInActivity.this.application.showToast("Must reconnect to server");
				}
			} else if(msg.authentificated == 2){
				GlobalVariables.setCurrrentAuthority(GlobalVariables.AUTHORITY_GUEST);
				GlobalVariables.setTemporaryKey("");
				this.application.showToast("Authentication fail because Key member has already logined");
			} else {
				GlobalVariables.setCurrrentAuthority(GlobalVariables.AUTHORITY_GUEST);
				GlobalVariables.setTemporaryKey("");
				this.application.showToast("Authentication failed");
			}
		}
	}
}
